<template>
    <div class="app-container">
  
      <div class="search-div">
        <el-form label-width="70px" size="small">
          <el-row>
            <el-col :span="4">
                <el-select v-model="searchObj.repoId" filterable placeholder="全部题库">
                  <el-option
                    v-for="item in option"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
            </el-col>
            <el-col :span="4">
                <el-select v-model="searchObj.quType" placeholder="全部类型">
                  <el-option
                    v-for="item in QuTypeOption"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
            </el-col>
            <el-col :span="4">
              <el-input style="width: 95%" v-model="searchObj.content" placeholder="关键字"></el-input>
            </el-col>
            <el-col :span="8">
              <el-form-item label="操作时间">
                <el-date-picker
                  v-model="createTimes"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="margin-right: 10px;width: 100%;"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="display:flex">
            <el-button type="primary" icon="el-icon-search" size="mini"  @click="fetchData()">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetData">重置</el-button>
          </el-row>
        </el-form>
      </div>
  
      <!-- 工具条 -->
      <div class="tools-div">
        <el-button type="success" icon="el-icon-plus" :disabled="$hasBP('bnt.page.add')  === false" size="mini" @click="add">添 加</el-button>
        <el-button class="btn-add" size="mini" :disabled="$hasBP('bnt.page.remove')  === false"  @click="batchRemove()" >批量删除</el-button>
      </div>
  
      <!-- 列表 -->
      <el-table
        v-loading="listLoading"
        :data="list"
        stripe
        border
        style="width: 100%;margin-top: 10px;"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection"/>
        <el-table-column
          label="序号"
          width="50"
          align="center">
          <template slot-scope="scope">
            {{ (page - 1) * limit + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="ChineseTypeQu" width="80" label="题目类型"/>
        <el-table-column prop="content" label="题目" show-overflow-tooltip/>
        <el-table-column prop="optionsA" label="选项A" show-overflow-tooltip/>
        <el-table-column prop="optionsB" label="选项B" show-overflow-tooltip/>
        <el-table-column prop="optionsC" label="选项C" show-overflow-tooltip/>
        <el-table-column prop="optionsD" label="选项D" show-overflow-tooltip/>
        <el-table-column prop="answer" label="正确答案" show-overflow-tooltip/>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作"  align="center" fixed="right" width="180">
          <template slot-scope="scope">
            <el-button type="primary" :disabled="$hasBP('bnt.page.update')  === false" icon="el-icon-edit" size="mini" @click="edit(scope.row.id)" title="修改"/>
            <el-button type="danger" :disabled="$hasBP('bnt.page.remove')  === false" icon="el-icon-delete" size="mini" @click="removeDataById(scope.row.id)" title="删除" />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
        :current-page="page"
        :total="total"
        :page-size="limit"
        style="padding: 30px 0; text-align: center;"
        layout="total, prev, pager, next, jumper"
        @current-change="fetchData"
      />
      <!--编辑表单（添加/编辑）-->
      <el-dialog title="编辑" :visible.sync="dialogVisible" width="40%" >
        <el-form ref="dataForm" :model="ElQu"  label-width="100px" size="small" style="padding-right: 40px;">
          <el-form-item v-if="PictureOrNo==='1'" label="图片预览">
              <template>
              <img :src="ElQu.url" width="100%" height=100%/>
            </template>
          </el-form-item>
          <el-form-item label="题干" prop="content">
            <el-input type="textarea" autosize v-model="ElQu.content"/>
          </el-form-item>
          <el-form-item label="是否携带图片" prop="content">
            <template>
              <el-radio v-model="PictureOrNo" label="1">是</el-radio>
              <el-radio v-model="PictureOrNo" label="2">否</el-radio>
            </template>
          </el-form-item>
          <el-form-item v-if="PictureOrNo==='1'" label="上传图片">
            <el-upload
            class="upload-demo"
            :headers="config"
            action="/dev-api/admin/el/qu/uploadImg"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg文件，且不超过2MB</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="题目类型" prop="content">
            <template>
              <el-radio v-model="ElQu.quType" label="1">单选题</el-radio>
              <el-radio v-model="ElQu.quType" label="2">多选题</el-radio>
              <el-radio v-model="ElQu.quType" label="3">判断题</el-radio>
              <el-radio v-model="ElQu.quType" label="4">论述题</el-radio>
            </template>
          </el-form-item>

          <el-form-item v-if="ElQu.quType==='1'|ElQu.quType==='2'" label="选项A" prop="optionsA">
            <el-input v-model="ElQu.optionsA"/>
          </el-form-item>
          <el-form-item v-if="ElQu.quType==='1'|ElQu.quType==='2'" label="选项B" prop="optionsB">
            <el-input v-model="ElQu.optionsB"/>
          </el-form-item>
          <el-form-item v-if="ElQu.quType==='1'|ElQu.quType==='2'" label="选项C" prop="optionsC">
            <el-input v-model="ElQu.optionsC"/>
          </el-form-item>
          <el-form-item v-if="ElQu.quType==='1'|ElQu.quType==='2'" label="选项D" prop="optionsD">
            <el-input v-model="ElQu.optionsD"/>
          </el-form-item>
          <el-form-item v-if="ElQu.quType==='2'" label="正确答案" prop="answer">
            <el-input v-model="ElQu.answer"/>
          </el-form-item>
          <el-form-item v-if="ElQu.quType==='1'" label="正确答案" prop="answer">
            <el-select v-model="ElQu.answer" placeholder="选择正确答案">
              <el-option
                v-for="item in QuOneAnswer"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="ElQu.quType==='3'" label="正确答案" prop="answer">
            <el-select v-model="ElQu.answer" placeholder="对/错">
              <el-option
                v-for="item in QuThreeAnswer"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="ElQu.quType==='4'" label="参考答案" prop="answer">
            <el-input type="textarea" autosize v-model="ElQu.answer"/>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" size="small" icon="el-icon-refresh-right">取 消</el-button>
          <el-button type="primary" icon="el-icon-check" @click="saveOrUpdate()" size="small">确 定</el-button>
        </span>
      </el-dialog>

      <!--题目添加到题库表单-->
      <el-dialog title="添加题目到题库" :visible.sync="dialogFormVisible">
        <!--表单中搜索功能-->
          <el-form label-width="70px" size="small">
            <el-row>
              <el-col :span="6">
                  <el-select v-model="searchObj.quType" placeholder="全部类型">
                    <el-option
                      v-for="item in QuTypeOption"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
              </el-col>
              <el-col :span="6">
                <el-input style="width: 95%" v-model="searchObj.content" placeholder="关键字"></el-input>
              </el-col>
              <el-col :span="12">
                <el-form-item label="操作时间">
                  <el-date-picker
                    v-model="createTimes"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    style="margin-right: 10px;width: 100%;"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row style="display:flex">
              <el-button type="primary" icon="el-icon-search" size="mini"  @click="fetchAllData()">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetAllDataWithoutRepo">重置</el-button>
            </el-row>
          </el-form>

        <el-table :data="listAll" height="250">
          <el-table-column  prop="ChineseTypeQu" label="题目类型" width="80"/>
          <el-table-column  prop="content" label="题目" show-overflow-tooltip/>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column  label="操作"  align="center" fixed="right">
            <template slot-scope="scope">
              <el-button type="success" :disabled="$hasBP('bnt.page.update')  === false" icon="el-icon-plus" size="mini" @click="AddQuToRepo(scope.row.id)" title="添加到题库"/>
            </template>
          </el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">完成</el-button>
        </div>
      </el-dialog>

    </div>
  </template>
  <style>
      .search-div {
          padding:10px;border: 1px solid #EBEEF5;border-radius:3px;
      }
      .tools-div {
          margin-top: 10px;padding:10px;border: 1px solid #EBEEF5;border-radius:3px;
      }
  </style>
  <script>
  import api from '@/api/El/qu'
  import { mapGetters } from 'vuex'
  const defaultForm = {
    id: '',
    url: '',
    content:'',
    createTime:'',
    updateTime:'',
    quType:'',
    optionsA:'',
    optionsB:'',
    optionsC:'',
    optionsD:'',
    answer:'',
  }
  export default {
    computed: {
      config() {
        return { token: this.token};
      },
    ...mapGetters([
      'token',
    ])
  },
    data() {
      return {
        listLoading: true, // 数据是否正在加载
        list: null, // banner列表
        listAll:null,
        total: 0, // 数据库中的总记录数
        page: 1, // 默认页码
        limit: 10, // 每页记录数
        searchObj: { // 查询题库封装名称
          quType:'',
          repoId:'',
          content:'',
        },
        searchAllObj:{
          quType:'',
          content:'',
        },
  
        createTimes: [],
  
        checkAll: false, // 是否全选
  
        dialogVisible: false,
        dialogFormVisible: false,
        ElQu: defaultForm,
        option: [{
          id: '',
          name: ''
        }],
        QuTypeOption:[
            {
                id: '1',
                name: '单选题'
            },
            {
                id: '2',
                name: '多选题'
            },
            {
                id: '3',
                name: '判断题'
            },
            {
                id: '4',
                name: '论述题'
            },
        ],

        QuOneAnswer:[ //单选题答案
            {
                id: 'A',
                name: 'A'
            },
            {
                id: 'B',
                name: 'B'
            },
            {
                id: 'C',
                name: 'C'
            },
            {
                id: 'D',
                name: 'D'
            },
        ],
        QuThreeAnswer:[ //判断题答案
            {
                id: '1',
                name: '对'
            },
            {
                id: '2',
                name: '错'
            },
        ],
        PictureOrNo: '2' //判断是否有图片


      }
    },
    // 生命周期函数：内存准备完毕，页面渲染成功
    mounted() {
      this.fetchData()
    },
  
    methods: {
      
      // 加载banner列表数据
      fetchData(page = 1) {
        this.page = page
        // 定义数字和题目的对应关系
        var numberMap = {
            "1": "单选题",
            "2": "多选题",
            "3": "判断题",
            "4": "论述题",
        };
        if(this.createTimes && this.createTimes.length ==2) {
            this.searchObj.createTimeBegin = this.createTimes[0]
            this.searchObj.createTimeEnd = this.createTimes[1]
        }
        api.GetRepoAndId().then(resp=>{
            this.option = resp.data
        })
        
        api.getPageList(this.page, this.limit, this.searchObj).then(
            response => {
                this.list = response.data.records
                // 遍历数据，将quType替换成对应的题目类型
                this.list.forEach(element => {
                    element.ChineseTypeQu = numberMap[element.quType]
                    if(element.quType === "3"){
                      if(element.answer === "1"){
                        element.answer = "对"
                      }else{
                        element.answer = "错"
                      }
                    }
                });
                
                this.total = response.data.total

                // 数据加载并绑定成功
                this.listLoading = false
            }
      )
    },
    //图片相关
    handleAvatarSuccess(res, file) {
        this.$message.success(res.message);
        this.ElQu.url = res.data.imgUrl;
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      // 重置查询表单
      resetData() {
        this.option = []
        this.searchObj={}
        this.createTimes = []
        this.fetchData()
      },
      resetAllData(){
        this.searchObj={}
        this.createTimes = []
        this.fetchAllData()
      },
      resetAllDataWithoutRepo(){
        this.searchObj.quType = ''
        this.searchObj.content = ''
        this.createTimes = []
        this.fetchAllData()
      },
  
      //批量删除
      batchRemove() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请选择要删除的记录！')
          return
        }
        var idList = []
        this.multipleSelection.forEach(item => {
          idList.push(item.id)
        })
        //先做个判断，看是删除某个题库中的题还是删除某个题目
          if(this.searchObj.repoId==""){
            this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              return api.DeleteQuList(idList)
            }).then((response) => {
              this.fetchData(this.page)
              this.$message.success(response.message || '删除成功')
            }).catch(() => {
              this.$message.info('取消删除')
            })
          }else{
            this.$confirm('此操作将从该题库中删除该题目, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              return api.DeleteQusToRepo(this.searchObj.repoId,idList)
            }).then((response) => {
              this.fetchData(this.page)
              this.$message.success(response.message || '删除成功')
            }).catch(() => {
              this.$message.info('取消删除')
            })
          }
      },
      // 根据id删除数据
      removeDataById(id){
         //先做个判断，看是删除某个题库中的题还是删除某个题目
          if(this.searchObj.repoId==""){
            this.$confirm('此操作将永久删除该题目, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              return api.DeleteQu(id)
            }).then((response) => {
              this.fetchData(this.page)
              this.$message.success(response.message || '删除成功')
            }).catch(() => {
              this.$message.info('取消删除')
            })
          }else{
            this.$confirm('此操作将从该题库中删除该题目, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              return api.DeleteQuToRepo(this.searchObj.repoId,id)
            }).then((response) => {
              this.fetchData(this.page)
              this.$message.success(response.message || '删除成功')
            }).catch(() => {
              this.$message.info('取消删除')
            })
          }
      },
  
      //弹出添加表单
      add(){
        this.ElQu = {}
        this.PictureOrNo='2'
        //判断是往题库中添加还是往数据库中添加(前者将现有的题目加入到题库中，后者为创建新题目)
        if(!this.searchObj.repoId){
          //创建新题目
          this.dialogVisible = true
        } else{ 
          //添加到题库
          this.fetchAllData()
          this.dialogFormVisible = true
        }
      },
      fetchAllData(){
          // 定义数字和题目的对应关系
          var numberMap = {
              "1": "单选题",
              "2": "多选题",
              "3": "判断题",
              "4": "论述题",
          };
          if(this.createTimes && this.createTimes.length ==2) {
            this.searchObj.createTimeBegin = this.createTimes[0]
            this.searchObj.createTimeEnd = this.createTimes[1]
          }
          this.searchObj.quType = this.searchAllObj.quType
          this.searchObj.content = this.searchAllObj.content
          api.getAll(this.searchAllObj).then(resp => {
            this.listAll = resp.data
            this.listAll.forEach(element => {
              element.ChineseTypeQu = numberMap[element.quType]
              if(element.quType === "3"){
                if(element.answer === "1"){
                  element.answer = "对"
                }else{
                  element.answer = "错"
                }
              }
          });
        })
      },
      //弹出编辑表单
      edit(id) {
        this.ElQu = {}
        api.SelectByID(id).then(resp => {
          this.ElQu = resp.data
          console.log(this.ElQu)
          //判断图片地址是否有内容
          if(this.ElQu.url === null){
            this.PictureOrNo = "2"
          }else{
            this.PictureOrNo = "1"
          }
        })
        this.dialogVisible = true
      },
      
      //添加或更新
      saveOrUpdate() {
        if (!this.ElQu.id) {
            this.save()
        } else {
            this.update()
        }
      },
  
      //添加
      save() {
        if(this.ElQu.quType==="3"||this.ElQu.quType==="4"){
          this.ElQu.optionsA = ''
          this.ElQu.optionsB = ''
          this.ElQu.optionsC = ''
          this.ElQu.optionsD = ''
        }
        api.Add(this.ElQu).then(resp => {
          this.$message.success('创建题目成功!')
          this.dialogVisible = false
          this.fetchData(this.page)

        })
      },
  
      //更新
      update() {
        api.Updata(this.ElQu).then(resp => {
          this.$message.success('更新成功!')
          this.dialogVisible = false
          this.fetchData(this.page)

        })
      },
      //批量删除的id
      handleSelectionChange(selection) {
        this.multipleSelection = selection
      },
      AddQuToRepo(id){
        api.AddQuToRepo(this.searchObj.repoId,id).then(resp => {
          this.$message.success('添加成功!')
          this.fetchAllData()
          this.fetchData(this.page)
        })
      },
    }
  }
  </script>